ships = [];

var text = document.getElementById("mainlabel");
var AW = 50;
var TW = 10;
var StateDS = 10;
var ViewDS = 10;
var NetDS = 10000;
var ShipR = 10;
var ShotR = 1;

// dojo.require("dojox.cometd");
// dojox.cometd.init( "/cometd/cometd" );

function init() {
	// should do dojo connection stuff here, find existing items.. draw them.. all that
	setInterval( "globalTick()", StateDS );
}

function makeLocalShip(){
	var canvas = document.getElementById("canvas");
	var ship = makeShip( 100 ,100 );
	canvas.appendChild( ship.getGraphic() );
	document.addEventListener("keydown", makeKeyboardControls( ship ), false );
}

var ticks = 0;
function globalTick(){
	ticks++;
	stateTick();
	viewTick();
	if ( ticks == 100 ){
		netTick();
		ticks = 0;
	}
}

function stateTick() {
  // update positions from velocities
  // update velocities from accelerations...
  var timeTick = StateDS/1000;

  for (var i=0;i<ships.length;i++) {
	  //    for (var j=i+1;j<ships.length;j++) {
      // collision detection
	  //      collide( ships[i], ships[j], timeTick );
	  //    }
	ships[i].updateState( timeTick );
  }
}
                
function viewTick() {
  // update sprite
  for (var i=0;i<ships.length;i++)
    ships[i].updateView();
  //  text.textContent = "dda: "+ships[0].dda+" thrust: "+ships[0].thrustLevel+" da: "+ships[0].da;
}

function netTick() {
  // update sprite
//   for (var i=0;i<ships.length;i++)
//     ships[i].updateNetwork();
}

// function collide( ship1, ship2, timeTick ) {
//   var x1i = ship1.x - ShipR;
//   var y1i = ship1.y - ShipR;
//   var x2i = ship2.x - ShipR;
//   var y2i = ship2.y - ShipR;
//   ship1.updateState( timeTick );
//   ship2.updateState( timeTick );
//   var x1f = ship1.x + ShipR;
//   var y1f = ship1.y + ShipR;
//   var x2f = ship2.x + ShipR;
//   var y2f = ship2.y + ShipR;
//   ship1.updateState( -1*timeTick );
//   ship2.updateState( -1*timeTick );

//   // calculate the intersection here
  
// }

// function distance(x1,y1,x2,y2) {
//   var dx=x1-x2;
//   var dy=y1-y2;
//   return Math.sqrt(dx*dx+dy*dy);
// }

function makeShip( x, y ) {
  var ship = new Ship(x,y,ships.length);
  ships.push( ship );
  return ship;
}
                
function makeKeyboardControls( ship ) {
  return function( event ){
    if ( event.keyCode == 37 ){ //left
      ship.rotate( -1 );
    } else if ( event.keyCode == 39 ){ //right
      ship.rotate( 1 );
    } else if ( event.keyCode == 38 ){ //up
      ship.thrust( 1 );
    } else if ( event.keyCode == 40 ){ //down
      ship.thrust( -1 );
    } else if ( event.keyCode == 32 ){ //space
      ship.thrust( 0 );
    }
  };
}
                
function mouseMoveHandler(event) {
  //  moveTo( event.clientX, event.clientY );
}
